<?php

namespace App\Models\Admin\Authority;

use App\Models\Admin\Apis\BaseApisModel;

class AuthorityApisModel extends BaseApisModel
{
    protected $table = 'authority_apis';

    /**
     * 根据角色id获取列表
     *
     * @param int   $authorityId
     * @param array $fields
     * @return array
     */
    public function getListByAuthorityId(int $authorityId, array $fields = self::QUERY_DEFAULT_FIELDS): array
    {
        return $this->select($fields)
            ->where('authority_id', $authorityId)
            ->get()
            ->toArray();
    }

    /**
     * 根据角色id获取api_id list
     *
     * @param int $authorityId
     * @return array
     */
    public function getApiIdListByAuthorityId(int $authorityId): array
    {
        return $this->where('authority_id', $authorityId)
            ->pluck('api_id')
            ->toArray();
    }

    public function getItemByAuthorityId(int $authorityId, array $fields = self::QUERY_DEFAULT_FIELDS)
    {
        return $this->select($fields)
            ->where('authority_id', $authorityId)
            ->get()
            ->toArray();
    }

    /**
     * 根据角色id删除角色权限
     *
     * @param int $authorityId
     * @return int
     */
    public function deleteItemByAuthorityId(int $authorityId): int
    {
        return $this->where('authority_id', $authorityId)
            ->delete();
    }

    /**
     * 添加数据
     *
     * @param $params
     * @return int
     */
    public function addItem($params): int
    {
        if (isset($params[0]) && is_array($params[0])) {
            foreach ($params as $index => $item) {
                $params[$index]['created_at'] = DATE_NOW;
            }
        } else {
            $params['created_at'] = DATE_NOW;
        }

        return $this->insert($params);
    }
}
